package com.example.chatzsyproject.utils;

import android.text.format.DateFormat;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.example.chatzsyproject.app.MyApplication;
import com.example.chatzsyproject.callback.UpLoadOSSCallBack;
import com.example.chatzsyproject.config.Config;

import java.io.File;
import java.util.Date;

/**
 * oss上传辅助类
 */
public class UploadHelper {

    private static OSS getOSSClient() {
        OSSCredentialProvider credentialProvider =
                new OSSPlainTextAKSKCredentialProvider(Config.AccessKeyId,
                        Config.AccessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(5 * 1000); // 连接超时，默认15秒。
        conf.setSocketTimeout(5 * 1000); // socket超时，默认15秒。
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
        conf.setMaxErrorRetry(2); //
        return new OSSClient(MyApplication.getInstance(), Config.AccessBucketUrl, credentialProvider, conf);
    }
    public  void upload(String path, final UpLoadOSSCallBack upLoadOSSCallBack) {
        final String ossPath= getObjectImageKey(path);
            OSS oss = getOSSClient();
                oss.asyncPutObject(new PutObjectRequest(Config.AccessBUCKET,
                                ossPath, path),
                new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) { // 上传成功
                        upLoadOSSCallBack.ossSuccCallBack(ossPath);
                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                          ServiceException serviceException) { // 上传失败
                        Log.e("zsy","失败");
                    }
                });
    }
    private static String getDateString() {
        return DateFormat.format("yyyyMM", new Date()).toString();
    }

    private static String getObjectImageKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("image/%s/%s.png", dateString, fileMd5);
    }

}
